import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from "/@/utils/authFunction";
import { ElMessage } from 'element-plus';

interface RowData {
    id: string;
    description?: string;
    modifier?: string;
    dept_belong_id?: string;
    update_datetime?: string;
    create_datetime?: string;
    sales_person: string;
    period: string;
    target_amount: number;
    actual_amount: number;
    achievement_rate: number;
    creator_id?: string;
}

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const pageRequest = async (query: UserPageQuery) => {
        try {
            return await api.GetList({
                ...query,
                ordering: query.sort?.[0]?.asc ? query.sort[0].prop : `-${query.sort?.[0]?.prop}`
            });
        } catch (error) {
            ElMessage.error('获取数据失败');
            return Promise.reject(error);
        }
    };
    
    const editRequest = async ({ form, row }: EditReq) => {
        try {
            return await api.UpdateObj({
                ...form,
                id: row.id
            });
        } catch (error: any) {
            // 处理服务器返回的错误信息
            if (error.response && error.response.data) {
                const errorData = error.response.data;
                if (errorData.period) {
                    // 特定处理期间错误
                    ElMessage.error(errorData.period[0] || '更新失败：同一销售人员在同一月份只能有一条业绩记录');
                } else {
                    // 处理其他错误
                    const errorMsg = Object.values(errorData).flat().join(', ');
                    ElMessage.error(errorMsg || '更新失败');
                }
            } else {
                ElMessage.error('更新失败');
            }
            return Promise.reject(error);
        }
    };
    
    const delRequest = async ({ row }: DelReq) => {
        try {
            if (!row?.id) {
                throw new Error('记录ID不存在');
            }
            return await api.DelObj(row.id);
        } catch (error) {
            ElMessage.error('删除失败');
            return Promise.reject(error);
        }
    };
    
    const addRequest = async ({ form }: AddReq) => {
        try {
            return await api.AddObj(form);
        } catch (error: any) {
            // 处理服务器返回的错误信息
            if (error.response && error.response.data) {
                const errorData = error.response.data;
                if (errorData.period) {
                    // 特定处理期间错误
                    ElMessage.error(errorData.period[0] || '添加失败：同一销售人员在同一月份只能有一条业绩记录');
                } else {
                    // 处理其他错误
                    const errorMsg = Object.values(errorData).flat().join(', ');
                    ElMessage.error(errorMsg || '添加失败');
                }
            } else {
                ElMessage.error('添加失败');
            }
            return Promise.reject(error);
        }
    };
    
    // 计算实际金额和达成率
    const calculateActualAmount = async () => {
        const form = crudExpose.getFormData();
        if (form.sales_person && form.period) {
            try {
                const res = await api.calculateActualAmount(form.sales_person, form.period);
                if (res.code === 2000 && res.data !== undefined) {
                    form.actual_amount = Number(res.data);
                    // 无论如何设置默认值为0，避免undefined或NaN
                    form.achievement_rate = 0;
                    if (form.target_amount && form.target_amount > 0) {
                        form.achievement_rate = Number(((form.actual_amount / form.target_amount) * 100).toFixed(2));
                    }
                    ElMessage.success('已自动计算实际金额和达成率');
                } else {
                    ElMessage.warning(res.msg || '计算实际金额失败');
                }
            } catch (error) {
                console.error('计算实际金额出错:', error);
                ElMessage.error('计算实际金额出错');
            }
        }
    };

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    add: {
                        text: "新增",
                        type: "primary",
                        icon: "plus",
                        show: auth('SalesPerformanceModelViewSet:Create'),
                    }
                }
            },
            table: {
                border: true,
                stripe: true,
                highlight: true,
            },
            search: {
                show: true,
                buttons: {
                    search: {
                        text: "搜索",
                        icon: "search",
                        show: auth('SalesPerformanceModelViewSet:Search')
                    },
                    reset: {
                        text: "重置",
                        icon: "refresh-right"
                    }
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 260,
                dropdown: {
                    more: {
                        text: '更多'
                    }
                },
                buttons: {
                    view: {
                        type: 'primary',
                        text: '查看',
                        icon: 'view',
                        order: 1,
                        show: auth('SalesPerformanceModelViewSet:Retrieve')
                    },
                    edit: {
                        type: 'warning',
                        text: '编辑',
                        icon: 'edit',
                        order: 2,
                        show: auth('SalesPerformanceModelViewSet:Update')
                    },
                    remove: {
                        type: 'danger',
                        text: '删除',
                        icon: 'delete',
                        order: 3,
                        show: auth('SalesPerformanceModelViewSet:Delete')
                    },
                    updateAmount: {
                        type: 'success',
                        text: '更新',
                        icon: 'Refresh',
                        order: 4,
                        show: auth('SalesPerformance:RefreshActualAmount'),
                        click: async ({ row }: { row: RowData }) => {
                            if (!row.id) {
                                ElMessage.warning('记录ID不存在，无法更新');
                                return;
                            }
                            
                            try {
                                // 调用后端更新实际金额的API
                                const res = await api.updateActualAmount(row.id);
                                
                                if (res.code === 2000) {
                                    // 更新成功
                                    ElMessage.success(res.msg || '实际金额已成功更新');
                                    // 刷新表格数据
                                    crudExpose.doRefresh();
                                } else {
                                    // 更新失败
                                    ElMessage.warning(res.msg || '更新实际金额失败');
                                }
                            } catch (error) {
                                console.error('更新实际金额出错:', error);
                                ElMessage.error('更新实际金额出错');
                            }
                        }
                    },
                },
            },
            form: {
                afterSubmit: ({ mode }) => {
                    // 表单提交后的回调
                    ElMessage.success(mode === 'add' ? '添加成功' : '编辑成功');
                },
                beforeSubmit: ({ form }) => {
                    // 表单提交前处理
                    // 确保达成率有默认值，防止为空或NaN
                    form.achievement_rate = 0;
                    if (form.target_amount && form.target_amount > 0 && form.actual_amount) {
                        // 确保达成率正确计算
                        form.achievement_rate = Number(((form.actual_amount / form.target_amount) * 100).toFixed(2));
                    }
                    return true;
                }
            },
            columns: {
                id: {
                    title: 'ID',
                    type: 'text',
                    column: {
                        width: 100,
                    },
                    form: {
                        show: false
                    }
                },
                sales_person: {
                    title: '销售人员',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 120,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '销售人员必填' }],
                        component: {
                            placeholder: '请输入销售人员姓名',
                            maxlength: 100,
                            onChange: () => {
                                calculateActualAmount();
                                return true;
                            }
                        },
                        helper: {
                            render: () => {
                                return "同一销售人员在同一月份只能有一条业绩记录";
                            }
                        }
                    },
                },
                period: {
                    title: '业绩周期',
                    type: 'date',
                    search: { show: true },
                    column: {
                        width: 120,
                        sortable: 'custom',
                        formatter: ({ value }) => {
                            if (!value) return '';
                            // 将日期格式化为年月显示
                            const date = new Date(value);
                            return `${date.getFullYear()}年${date.getMonth() + 1}月`;
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '业绩周期必填' }],
                        component: {
                            type: 'month',
                            valueFormat: "YYYY-MM-DD",
                            placeholder: '请选择业绩月份',
                            onChange: () => {
                                calculateActualAmount();
                                return true;
                            }
                        },
                        helper: {
                            render: () => {
                                return "选择月份后会自动计算该月销售业绩，同一销售人员在同一月份只能有一条业绩记录";
                            }
                        }
                    },
                },
                target_amount: {
                    title: '目标金额',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '目标金额必填' }],
                        component: {
                            placeholder: '请输入目标金额',
                            min: 0,
                            precision: 2,
                            onChange: (value: number) => {
                                const form = crudExpose.getFormData();
                                // 设置默认值为0
                                form.achievement_rate = 0;
                                if (value && value > 0 && form.actual_amount) {
                                    form.achievement_rate = Number(((form.actual_amount / value) * 100).toFixed(2));
                                }
                                return true;
                            }
                        },
                    },
                },
                actual_amount: {
                    title: '实际金额',
                    type: 'number',
                    search: { show: false },
                    column: {
                        width: 120,
                        sortable: 'custom',
                        formatter: ({ value }) => {
                            return value ? `¥${value.toLocaleString()}` : '¥0';
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '实际金额必填' }],
                        component: {
                            placeholder: '实际金额将根据销售人员和业绩周期自动计算',
                            min: 0,
                            precision: 2,
                            onChange: (value: number) => {
                                const form = crudExpose.getFormData();
                                // 设置默认值为0
                                form.achievement_rate = 0;
                                if (form.target_amount && form.target_amount > 0) {
                                    form.achievement_rate = Number(((value / form.target_amount) * 100).toFixed(2));
                                }
                                return true;
                            }
                        },
                        helper: {
                            render: () => {
                                return "选择销售人员和业绩周期后，系统会自动计算该销售人员在该周期内完成订单的总金额";
                            }
                        }
                    },
                },
                achievement_rate: {
                    title: '达成率',
                    type: 'text',
                    column: {
                        width: 100,
                        sortable: 'custom',
                        formatter: ({ value }) => {
                            // 确保值存在且不是NaN
                            return (value !== undefined && !isNaN(value)) ? `${value}%` : '0%';
                        }
                    },
                    form: {
                        show: false
                    }
                },
                description: {
                    title: '备注',
                    type: 'textarea',
                    column: {
                        minWidth: 150,
                    },
                    form: {
                        component: {
                            placeholder: '请输入备注信息',
                            maxlength: 255,
                            showWordLimit: true,
                        }
                    }
                },
                create_datetime: {
                    title: '创建时间',
                    type: 'datetime',
                    column: {
                        width: 180,
                        sortable: 'custom',
                    },
                    form: {
                        show: false
                    }
                },
                update_datetime: {
                    title: '更新时间',
                    type: 'datetime',
                    column: {
                        width: 180,
                        sortable: 'custom',
                    },
                    form: {
                        show: false
                    }
                }
            }
        }
    };
} 